import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../views/Layout.vue'
import Cookies from 'js-cookie'

Vue.use(VueRouter)

const routes = [
    // 登陆

  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login/Login.vue')
  },

  {
    path: '/',
    name: 'layout',
    component: Layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        name: 'Home',
        component: () => import('@/views/home/HomeView.vue')
      },
      //  User
      {
        path: 'user',
        name: 'User',
        component: () => import('@/views/user/User.vue')
      },
      {
        path: 'updateUser',
        name: 'UpdateUser',
        component: () => import('@/views/user/UpdateUser.vue')
      },
      //  Room
      {
        path: 'borrow',
        name: 'Borrow',
        component: () => import('@/views/user/Borrow.vue')
      },
      {
        path: 'reback',
        name: 'Reback',
        component: () => import('@/views/user/Reback.vue')
      },
      {
        path: 'check',
        name: 'Check',
        component: () => import('@/views/user/Check.vue')
      },
      {
        path: 'addRoom',
        name: 'AddRoom',
        component: () => import('@/views/user/AddRoom.vue')
      },
      {
        path: 'serviceRoom',
        name: 'ServiceRoom',
        component: () => import('@/views/user/ServiceRoom.vue')
      },

      //  admin
      {
        path: 'adminlist',
        name: 'Adminlist',
        component: () => import('@/views/admin/List.vue')
      },
      {
        path: 'addAdmin',
        name: 'AddAdmin',
        component: () => import('@/views/admin/Add.vue')
      },
      {
        path: 'editAdmin',
        name: 'EditAdmin',
        component: () => import('@/views/admin/Edit.vue')
      }
    ]
  },
  {
    path: "*",
    component:() => import('@/views/404')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//    路由守卫
router.beforeEach((to,from,next) => {
  if(to.path === '/login') next()
  const admin = Cookies.get("admin")
  if (!admin && to.path !== '/login') return next("/login")
  // 访问/home的时候，并且cookie里面存在数据的时候，才放行
  next()
})

export default router
